/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.module.datasource.biz.adapter.admin;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.elsfs.cloud.common.controller.ControllerConfig;
import org.elsfs.cloud.common.controller.LogicRepositoryCrudController;
import org.elsfs.cloud.common.util.exception.ElsfsException;
import org.elsfs.cloud.module.datasource.biz.entity.GenFieldType;
import org.elsfs.cloud.module.datasource.biz.repository.GenFieldTypeRepository;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 表列属性管理
 *
 * @author zeng
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/genFieldType")
@Tag(description = "genFieldType", name = "列属性类型管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class GenFieldTypeController
    extends LogicRepositoryCrudController<
        GenFieldType, GenFieldType, GenFieldType, GenFieldType, GenFieldTypeRepository, String> {
  @Override
  protected ControllerConfig getConfig() {
    return super.getConfig().list(true);
  }

  @Override
  protected void check(GenFieldType entity, boolean isUpdate) {
    List<GenFieldType> list =
        repository.list(
            Wrappers.lambdaQuery(GenFieldType.class)
                .ne(GenFieldType::getColumnType, entity.getColumnType()));
    if (list.isEmpty()) {
      return;
    }
    if (!isUpdate) {
      throw new ElsfsException("列属性类型已存在");
    }
    for (var type : list) {
      if (!Objects.equals(type.getId(), entity.getId())) {
        throw new ElsfsException("列属性类型已存在");
      }
    }
  }
}
